#include <ProtocolHandler.h>

#include <LiquidCrystal.h>
#include <SoftwareSerial.h>
#include <avr/pgmspace.h>
#include <math.h>
#include <sstream>
#include <stdlib.h>
SoftwareSerial lcdSerial(8,7);
enum {
  T_KELVIN=0,
  T_CELSIUS=1,
  T_FAHRENHEIT=2
};
int temperatureSensor = A0;
void setup(){lcdSerial.begin(9600);}
void loop(){
  double temp = Temperature(0,T_CELSIUS,3740,298.15,22000,10000);
  //double temp = TemperatureWTable(0, 10000);
  printToLCD(micros(),2);
  delay(10000);
}

void printToLCD(double message, int precision){
  lcdSerial.write(0xFE);   
  lcdSerial.write(0x01);
  lcdSerial.print(message,precision);
}

float Temperature(int AnalogInputNumber,int OutputUnit,float B,float T0,float R0,float R_Balance)
{
  float R,T;

  R=(1024.0f*R_Balance/float(analogRead(AnalogInputNumber)))-R_Balance;
  T=1.0f/(1.0f/T0+(1.0f/B)*log(R/R0));

  switch(OutputUnit) {
    case T_CELSIUS :
      T-=273.15f;
    break;
    case T_FAHRENHEIT :
      T=9.0f*(T-273.15f)/5.0f+32.0f;
    break;
    default:
    break;
  };

  return T;
}

float TemperatureWTable(int AnalogInputNumber, float R_Balance)
{
  long T;
  int R;
  
  const long T_table[]  = {-10, -5, 0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50};
  const long R_table[]  = {107900, 84250, 66240, 52450, 41810, 33550, 27080, 22000, 17970, 14770, 12200, 10120, 8447};

  R=(1024*R_Balance/analogRead(AnalogInputNumber))-R_Balance;
  
  int index_left;
  int index_right;
  long d_min = R_table[0] - R; 

  for( int i=0; i<13; i++){
    long diff = R_table[i] - R;
    if(diff>0){
      if(diff<d_min){
        d_min = diff;
        index_left = i;
      }
    }
  }
  
  index_right = index_left + 1;
  
  T= T_table[index_right]+(((T_table[index_left]-T_table[index_right])*(R-R_table[index_right]))/(R_table[index_left]-R_table[index_right]));

  return T;
}
